﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Models;
using DAL;
using System.IO;

namespace StudentManager
{
    public partial class Form1 : Form
    {
        private string filename = string.Empty;
        private List<Student> stuList = new List<Student>();
        private StudentService service = new StudentService();
        private List<Student> queryList = new List<Student>();
        private string photoPath = string.Empty;
        private string photoName = string.Empty;
        private int flag = 0;//0是增加  1是编辑
        public Form1()
        {
            InitializeComponent();
            this.groupBox2.Enabled = false;

        }
        //关闭动作
        private void btnClose_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("退出之后需要保存么","系统提示",MessageBoxButtons.OKCancel,MessageBoxIcon.Information);
            if (result == DialogResult.OK) { 
                //1、清空
                File.WriteAllText(filename,string.Empty);
                //2、写入
                StreamWriter sw = new StreamWriter(filename,true,Encoding.Default);
                string line = string.Empty;
                foreach(Student s in stuList){
                    line = s.Sno + ',' + s.Sname + ',' + s.Phone + ',' + s.Email + ',' + s.Sex + ',' + s.pathinfo;
                    sw.WriteLine(line);
                }
                sw.Close();
                //3、写入完成
                MessageBox.Show("写入完成", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            Close();
        }

    
        #region 导入文件
        private void btnImport_Click(object sender, EventArgs e)
        {
            //导入文件 -读取文件 -list<Student>-显示到datagridview、
            //选择文件  
            OpenFileDialog of = new OpenFileDialog();
            of.Filter="CSV文件（*.csv）|*.csv|TXT文件（*.txt）|*.txt|所有文件(*.*)|*.*";
            if (of.ShowDialog() == DialogResult.OK) {
                filename = of.FileName;

            }
            //读取文件
            try
            {
                FileOperator fo = new FileOperator();
                stuList = fo.ReadFile(filename);
            }
            catch (Exception ex)
            {

                MessageBox.Show("读取数据失败"+ex.Message,"数据读取",MessageBoxButtons.OK,MessageBoxIcon.Asterisk);
            }
            //显示学生信息
            dgView.DataSource = null;
            dgView.DataSource = stuList;
            //显示明细
            Student st = service.GetStudentBySno(dgView.Rows[0].Cells[0].Value.ToString(),stuList);
            LoadDataToDetail(st);


        }
        #endregion
        //载入数据
        private void LoadDataToDetail(Student stu) {
            txtSno.Text = stu.Sno;
            txtName.Text = stu.Sname;
            txtPhone.Text = stu.Phone;
            txtEmail.Text = stu.Email;
            if (stu.Sex == "男") rbMale.Checked = true; else rbFemal.Checked = true;
            if (string.IsNullOrWhiteSpace(stu.pathinfo)) {
                return;
            }else{
                picHeader.BackgroundImage=Image.FromFile(stu.pathinfo);
            }
        }

        //添加信息
        private void btnAdd_Click(object sender, EventArgs e)
        {
            flag = 0;
            DisableButton();
            txtName.Text = null;
            txtEmail.Text = null;
            txtPhone.Text = null;
            txtSno.Text = null;
            txtSno.Focus();
        }
        //编辑信息
        private void btnEdit_Click(object sender, EventArgs e)
        {
            flag = 1;
            txtSno.Enabled = false;
            DisableButton();
        }
        //删除信息
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (stuList.Count == 0) return;
            else if (dgView.CurrentRow.Selected == false) return;
            else
            {
                try
                {
                    string info = "你确定删除学号为" + dgView.CurrentRow.Cells[0].Value.ToString() + "的信息么";
                    DialogResult result = MessageBox.Show("删除成功", "系统消息", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                    if (result == DialogResult.OK)
                    {
                        service.delStudent(dgView.CurrentRow.Cells[0].Value.ToString(), stuList);
                    }
                    btnCancel_Click(null, null);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("删除失败，失败原因" + ex.Message, "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        //提交信息
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            Student s =  new Student{ 
                                    Sno=txtSno.Text,
                                    Sname=txtName.Text,
                                    Phone=txtPhone.Text,
                                    Email=txtEmail.Text,
                                    Sex=rbFemal.Checked==true?"女":"男",
                                    pathinfo=null
                                };

            if(picHeader.BackgroundImage!=null){
                s.pathinfo = PhotoSave(photoPath);
            }
            switch (flag)
            {
                
                case 0:
                    try
                    {
                        service.saveStudnet(s  ,stuList );
                        MessageBox.Show("保存成功" , "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        btnCancel_Click(null,null);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("保存失败，失败原因"+ex.Message,"系统消息",MessageBoxButtons.OK,MessageBoxIcon.Information);
                    }
                    break;
                case 1:
                    try
                    {
                        service.UpdateStudent(s  ,stuList );
                        MessageBox.Show("更新成功" , "系统消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        btnCancel_Click(null,null);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("保存失败，失败原因"+ex.Message,"系统消息",MessageBoxButtons.OK,MessageBoxIcon.Information);
                    }
                    break;
                default:
                    break;
            }
            EnableButton();
        }
        //取消信息
        private void btnCancel_Click(object sender, EventArgs e)
        {
            EnableButton();
            dgView.DataSource = null;
            dgView.DataSource = stuList;
            if (stuList.Count != 0) {
                Student s = service.GetStudentBySno(dgView.Rows[0].Cells[0].Value.ToString(), stuList);
                LoadDataToDetail(s);
            }
        }
        //datagridview 改变 明细
        private void dgView_SelectionChanged(object sender, EventArgs e)
        {
            if (dgView.Rows.Count == 0) return;
            else if (dgView.CurrentRow.Selected == false) return;
            else
            {
                Student ss = service.GetStudentBySno(dgView.CurrentRow.Cells[0].Value.ToString(), stuList);
                LoadDataToDetail(ss);
            }
        }
        //学号改变 查询
        private void tbSno_TextChanged(object sender, EventArgs e)
        {
            string txtno = tbSno.Text ;
            //queryList = (List<Student>)dgView.DataSource;
            if (!string.IsNullOrWhiteSpace(txtno)) {
                queryList = service.GetAllBySno(txtno, stuList);
            }
            dgView.DataSource = queryList;

        }
        //姓名改变查询
        private void tbName_TextChanged(object sender, EventArgs e)
        {
            string txtName = tbName.Text;
           // queryList = (List<Student>)dgView.DataSource;
            if (!string.IsNullOrWhiteSpace(txtName))
            {
                queryList = service.GetAllByName(txtName, stuList);
            }
            dgView.DataSource = queryList;
        }
        //电话变更查询
        private void tbPhone_TextChanged(object sender, EventArgs e)
        {
            string txtPhone = tbPhone.Text;
            //queryList = (List<Student>)dgView.DataSource;
            if (!string.IsNullOrWhiteSpace(txtPhone))
            {
                queryList = service.GetAllByPhone(txtPhone, stuList);
            }
            dgView.DataSource = queryList;
        }

        //激活按钮
        private void EnableButton() {
            this.btnImport.Enabled = true;
            this.btnAdd.Enabled = true;
            this.btnEdit.Enabled = true;
            this.btnDelete.Enabled = true;

            this.groupBox2.Enabled = false;
        }
        //关闭按钮
        private void DisableButton() {
            this.btnImport.Enabled = false;
            this.btnAdd.Enabled = false;
            this.btnEdit.Enabled = false;
            this.btnDelete.Enabled = false;

            this.groupBox2.Enabled = true;
        }
        //选择照片
        private void btnPic_Click(object sender, EventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            of.Filter = "图片|*.jpg;*.png";
            if (of.ShowDialog() == DialogResult.OK) {
                photoPath = of.FileName;
                picHeader.BackgroundImage = Image.FromFile(photoPath);
            }
        }

        public string PhotoSave(string pp) {
            string path = service.PhotoPath(photoPath);
            photoName = ".\\images\\"+path;
            Bitmap bm = new Bitmap(picHeader.BackgroundImage);
            bm.Save(photoName, picHeader.BackgroundImage.RawFormat);
            bm.Dispose();
            return photoName;
            
        }
    }
}
